package cc.facesign.acl.service.impl;

import cc.facesign.acl.bean.AclRole;
import cc.facesign.acl.mapper.TblUserMapper;
import cc.facesign.acl.service.AclMenuService;
import cc.facesign.acl.service.TblUserService;
import cc.facesign.common.exception.FacesignException;
import cc.facesign.common.utils.bean.JwtUtil;
import cc.facesign.common.utils.bean.R;
import cc.facesign.security.bean.LoginUser;
import cc.facesign.security.bean.TblUser;
import cc.facesign.servicebase.utils.RedisCache;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author acdongla
 * @since 2022-05-02
 */
@Service
@Transactional
public class TblUserServiceImpl extends ServiceImpl<TblUserMapper, TblUser> implements TblUserService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private AclMenuService menuService;

    @Autowired
    private RedisCache redisCache;

    @Override
    public R login(TblUser user) {

        // 封装认证对象
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getPhone(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if (authenticate == null) {
            throw new FacesignException(R.ERROR, "认证失败");
        }

        // 获取用户信息-获取token-完整用户信息存入redis
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getId();
        String jwt = JwtUtil.createJWT(userId);
        redisCache.setCacheObject("login:"+userId, loginUser, 8, TimeUnit.HOURS);

        return R.ok().data("token", jwt);
    }

    @Override
    public List<AclRole> getAllRolesByUserId(String userId) {
        return baseMapper.getAllRolesByUserId(userId);
    }

    @Override
    public String getRid(String userId) {
        return baseMapper.getRid(userId);
    }


}
